﻿define [
    'jquery'
    'use!underscore'
    'use!backbone'
    'namespace'
    'collections/album'
    'views/photo'
    'views/addPhoto'
], ($, _, Backbone, global, Album, PhotoView, AddView) ->
  class AlbumView extends Backbone.View
    el: $('#album')
    initialize: ->
      Album.on('reset', =>
          @collection = Album
          if $('#albums:empty').length > 0
              _.each _.uniq(@collection.pluck('type')), (album) ->
                $('<option />',
                  text: album
                  value: album
                ).appendTo '#albums'
          last_choice = localStorage.getItem('photo_album') or 'bike'
          $('#albums').get(0).selectedIndex = $('option', '#albums').index($('option[value=\'' + last_choice + '\']', '#albums'))
          @initCallback and @initCallback.func(@initCallback.args)
      )
      
    render: (album) ->
      if @collection then @showAlbum(album)
      else 
        Album.fetch()
        @initCallback = {func: @showAlbum, args:album}
      this

    showAlbum: (album) =>
      album = album or localStorage.getItem('photo_album') or 'bike'
      modelsToRender = _.filter(@collection.models, (item) ->
        item.get('type') is album
      )
      _.each modelsToRender, ((photoModel) ->
        photo = new PhotoView(model: photoModel)
        @$el.append photo.render('show').el
      ), this

    events:
      'click #addPhoto': 'createPhoto'
      'change #albums': 'changeAlbum'

    createPhoto: (e) ->
      e.preventDefault()
      return  if $('#add.photo').length > 0
      newView = new AddView()
      $('.photo:first').before newView.render('edit').el
      global.app.router.navigate 'Photo/Create'

    changeAlbum: (e) ->
      @$el.find('figure').remove()
      # TODO: Dispose every Backbone.View
      localStorage.setItem 'photo_album', e.target.value
      @render e.target.value

  new AlbumView()